<?php
	ob_start();
	session_start();

	if(! (isset($_SESSION['authorized']) && $_SESSION['authorized'] == true))
	{
		header("location: login.php?url={$_SERVER['PHP_SELF']}");
	}	

	function random_image(){
		$image_directory = "images/";
		$array = array();
		
		if(is_dir($image_directory)){
			if($handle = opendir($image_directory)){
				while(false !== ($entry = readdir($handle))){
					if($entry != "." && $entry != ".."){
						array_push($array, $entry);
					}
				}
			}
		}

		print "\"images/" . $array[rand(0, count($array)-1)] ."\"";
		closedir($image_directory);
	}
?>

<html>
	<head>
		<title>Main Page</title>

		<script type="text/javascript">
			var request = new XMLHttpRequest();

			function sendQuestion(){
				var url = "insert_question.php";
				var question = document.getElementsByName("question")[0].value;
				var filename = document.getElementsByTagName("img")[0].src;
				var params = "question=" + question + "&filename=" + filename;

				console.log("Question: " + question);
				console.log("Filename: " + filename);
				
				request.open("POST", url, true);

				request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				//http.setRequestHeader("Content-length", params.length);
				//http.setRequestHeader("Connection", "close");

				request.onreadystatechange = function(){
					if(request.readyState == 4 && request.status == 200){
						alert("Question sent!");
					}
				}

				request.send(params);
			}
		</script>
	</head>

	<body>
		<center>
			<table>
				<tr>
					<td align="center"><img src=<?php random_image() ?>></td> 
				</tr>
				<tr>
					<td align="center">Please insert your question: <input name="question" type="text" size="45"></td>
				</tr>
				<tr>
					<td align="center"><input type="submit" value="Go!" onClick="sendQuestion()"></td>
				</tr>
				<tr>
					<td align="center"><a href="logout.php">Logout</a></td>
				</tr>
			<table>
		</center>	
	</body>
</html>